package com.tn.openrpc.jms;

import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * An implementation of <code>MessageProcessor</code> that will echo back the JMS reply-to header from a message as a
 * <code>TextMessage</code>.
 */
public class ReplyToEchoProcessor implements MessageProcessor<Message>
{
  private static final Logger LOGGER = LoggerFactory.getLogger(ReplyToEchoProcessor.class);

  private ConnectionFactory connectionFactory;

  /**
   * Creates a new <code>ReplyToEchoProcessor</code>.
   *
   * @param connectionFactory the connection factory used to connect to the destinations.
   */
  public ReplyToEchoProcessor(ConnectionFactory connectionFactory)
  {
    this.connectionFactory = connectionFactory;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void processMessage(final Message message) throws MessageProcessingException
  {
    try
    {
      LOGGER.debug("Echoing reply-to destination: {}", message.getJMSReplyTo());

      new JmsTemplate(connectionFactory).send(
        message.getJMSReplyTo(),
        new MessageCreator()
        {
          @Override
          public Message createMessage(Session session) throws JMSException
          {
            Message response = session.createTextMessage(message.getJMSReplyTo().toString());
            response.setJMSCorrelationID(message.getJMSCorrelationID());
            return response;
          }
        }
      );
    }
    catch (JMSException e)
    {
      LOGGER.error("An error occurred reading the message contents.", e);
    }
    catch (RuntimeException e)
    {
      LOGGER.error("An error occurred processing message.", e);
    }
  }
}
